package com.shindo.structure.class01;

/**
 * 有序数组中找到 <= num 最右位置
 */
public class Code05_BSNearRight {

    public static int nearestIndex(int[] arr, int value) {
        int L = 0;
        int R = arr.length - 1;
        int index = -1;//记录最右的下标
        while (L <= R) {
            int mid = L + ((R - L) >> 1);
            if (arr[mid] <= value) {
                index = mid;
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        return index;
    }

    public static int test(int[] arr, int value) {
        for (int i = arr.length - 1; i >= 0; i--) {
            if (arr[i] <= value) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{1, 3, 5, 8, 11, 12, 18, 23, 25};
        int value = 0;
        System.out.println(test(arr, value));
        System.out.println(nearestIndex(arr, value));
    }
}
